<?PHP

class OP_RecentPostsWidget extends OP_WidgetTemplate{
	function render(){
		$title = empty( $this->values['title'] ) ? __( 'Recent Posts' ) : apply_filters('widget_title', $this->values['title']);
		if($posts_page = get_option('page_for_posts')){
			$posts_page = get_permalink($posts_page);
			$title = '<a href="'.$posts_page.'">'.$title.'</a>';	
		}
		
		if ( !$quantity = (int) $this->values['quantity'] )
			$quantity = 10;
		else if ( $quantity < 1 )
			$quantity = 1;
		else if ( $quantity > 15 )
			$quantity = 15;

		$r = new WP_Query(array('showposts' => $quantity, 'what_to_show' => 'posts', 'nopaging' => 0, 'post_status' => 'publish'));
		if ($r->have_posts()){
			echo $this->values['before_title'] . $title . $this->values['after_title'],
				'<ul>';
			while ($r->have_posts()){
				$r->the_post();
				echo '<li><a href="';
				the_permalink();
				echo '">';
				
				if (get_the_title()){
					the_title();
				}
				else{
					the_ID();
				}
				echo '</a></li>';
			}
			echo '</ul>';
			wp_reset_query();
		}
	
	/*	if ( '%BEG_OF_TITLE%' != $values['before_title'] )
		wp_cache_add('widget_op_recent_posts', ob_get_flush(), 'widget');*/
	}
	
	function do_post($post){
		$title = strip_tags(stripslashes($post["title"]));
		$quantity = (int) $post["quantity"];
	
		return compact( 'title','quantity');
	}
	
	function options(){
		$title = attribute_escape($this->values['title']);

		echo '<p><label for="op_recent_posts-title-'.$this->values['number'].'">'._e('Title:').' <input class="widefat" id="multi_recent_posts-title-'.$this->values['number'].'" name="widget_op_recent_posts['.$this->values['number'].'][title]" type="text" value="'.$this->values['title'].'" /></label></p>',
			'<p>',
				'<label for="op_recent_posts-quantity-'.$this->values['number'].'">'._e('Number of posts to show:').' <input style="width: 25px; text-align: center;" id="op_recent_posts-quantity-'.$this->values['number'].'" name="widget_op_recent_posts['.$this->values['number'].'][quantity]" type="text" value="'.$this->values['quantity'].'" /></label>',
				'<br />',
					'<small>(at most 15)</small>',
			'</p>',
			'<input type="hidden" name="widget_op_recent_posts['.$this->values['number'].'][submit]" value="1" />';
	}
}

$widget = new OP_Widget('recent_posts');
$widget->setMeta('OP Recent Posts',"The most recent posts on your blog");
$widget->setDefaults(array('title'=>'','quantity'=>5));

$opw_recent_posts = new OP_RecentPostsWidget($widget);
add_action('widgets_init', array($opw_recent_posts, 'init'));

/**
 * Flush cache when 'save_post','deleted_post', or 'switch_theme' occurs
 */
function op_flush_widget_op_recent_posts() {
	wp_cache_delete('widget_op_recent_posts', 'widget');
}

add_action('save_post', 'op_flush_widget_op_recent_posts');
add_action('deleted_post', 'op_flush_widget_op_recent_posts');
add_action('switch_theme', 'op_flush_widget_op_recent_posts');


?>